﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Service.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly SqlServerDbContext db;

        public UserController(SqlServerDbContext context)
        {
            this.db = context;
        }

        [HttpGet]
        [Route("GetAll")]
        public IEnumerable<Domain.Dtos.User> Get1All()
        {
            var dto = new List<Domain.Dtos.User>();
            var list = db.Set<User>().AsEnumerable();
            if (list.Any())
            {
                list.ToList().ForEach(c =>
                {
                    var model = new Domain.Dtos.User
                    {
                        Id = c.Id,
                        UserName = c.UserName,
                        UserPwd = c.UserPwd,
                        ShortMessage = c.ShortMessage
                    };
                    dto.Add(model);
                });
            }        
            return dto;
        }

        [HttpGet]
        [Route("GetById")]
        public Domain.Dtos.User GetById(long Id)
        {
            var model = db.Set<User>().FirstOrDefault(t => t.Id == Id);
            var req = new Domain.Dtos.User
            {
                Id = model.Id,
                UserName = model.UserName,
                UserPwd = model.UserPwd,
                ShortMessage = model.ShortMessage
            };
            return req;
        }

        [HttpPost]
        [Route("AddUser")]
        public ActionResult< bool > Add([FromBody] Domain.Dtos.AddUse dto)
        {
            var use = new User
            {               
                UserName = dto.UserName,
                UserPwd = dto.UserPwd,
                ShortMessage = dto.ShortMessage
            };
          db.Add<User>(use);
         var result=   db.SaveChanges();
            if (result>0)
            {
                return true;
            }
            else
            {
                return false;
            }                      
        }
    }
}
